package com.westvalley.common.kit;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;

public class EntityKit {
	private final static String METHOD_SET = "set";
	private final static String METHOD_GET = "get";
	
	public static <T> T newInstance(Class<T> clazz){
		T entity = null;
		try{
			entity = clazz.newInstance();
		}catch (Exception e) {
			LogKit.error("创建失败:",e);
		}
		return entity;
	}
	
	public static <T> T setValue(T entity,Method method,Object value) throws Exception{
		Class<?> parameterTypeClass = method.getParameterTypes()[0];
		entity.getClass().getMethod(method.getName(), parameterTypeClass).invoke(entity, CastKit.cast(parameterTypeClass, value));
		return entity;
	}
	
	public static <T> T setValue(T entity,String propertyName,Object value) throws Exception{
		Method method = entity.getClass().getMethod(METHOD_SET+StrKit.firstCharToUpperCase(propertyName), value.getClass());
		return setValue(entity,method,value);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getValue(Object entity,Method method) throws Exception{ 
		return (T) CastKit.cast(method.getReturnType(),method.invoke(entity));
	}
	
	public static <T> T getValue(Object entity,String propertyName) throws Exception{ 
		Method method = entity.getClass().getMethod(METHOD_GET+StrKit.firstCharToUpperCase(propertyName));
		return getValue(entity,method);
	}
	
	public static List<String> getCols(Class<?> clazz){
		List<String> listCols = new ArrayList<String>();
		for(Field field : clazz.getDeclaredFields()){
			listCols.add(field.getName());
		}
		return listCols;
	}
	
	public static Map<String,Object> getFieldMap(Object obj){
		Map<String,Object> fieldMap = Maps.newLinkedHashMap();
		if(obj!=null){
			for(Field field : obj.getClass().getDeclaredFields()){
				try{
					field.setAccessible(true);
					fieldMap.put(field.getName(), field.get(obj));
				}catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
		return fieldMap;
	}
	
}
